// packageA/pages/userList/userList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
//import { HTML5_FMT } from '../../../libs/moment.min.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //项目选择框
    showProject:false,
    //项目选择数据
    projectList:[],
    //项目id
    projectId:null,
    //项目名称
    projectName:'全部',
    //搜索关键词
    searchValue:'',
    //权限
    authority: null,


       // 当前展开项的ID（初始不展开任何项）   
       activeName: null, 
       //任务列表
       taskList:[], 
       //显示任务详情
       addTaskShow:false,
       //任务内容
       editTaskObj:{},
       //项目列表
       departList:[],
      //选择项目
      projectShow:false,
      //已选择项目列表
      listProjectMap:{},
      //点击单元行，任务信息默认禁用
      isDisable:true,
      disabled:false,
      showProjectSelect:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      authority: app.globalData.authority
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('人员列表传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
    }

    //获取列表数据
    this.getList();
  },

  editFunc(){
    this.setData({
      isDisable:false
    })
  },

    //选择任务类型
    onchangetype(event){
      console.log("event")
      console.log(event)
      let taskType='editTaskObj.taskType';
      this.setData({
        [taskType]: event.detail,
      })
  },

    //获取输入的数量
    onChangePartNum(event) {  
      console.log("event");
      console.log(event);
      let names = 'editTaskObj.taskObj.imgCountRequire'
      this.setData({
        [names]: event.detail
      })
    },
  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });
    let param={}
    console.log(this.data.projectId);
    if(this.data.projectId != null && this.data.projectId != "" && this.data.projectId != -1){
      param.projectId = this.data.projectId
    }
    console.log(param);
    CommonService.findTaskList(param).then(res => {
      console.log('人员列表');
      console.log(res);
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        Toast.clear();
        let result = []
        result=res.data.data.result;
        console.log('人员列表');
        console.log(result);
        this.setData({
          taskList:result
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          Toast.clear();
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      Toast.clear();
      this.setData({
        showNothing: true
      })
    })
  },

//选择项目事件
onChangeProjectCheck({currentTarget}){
  let detail=currentTarget.dataset.detail;
  let list=this.data.departList;
  let listMap=this.data.listProjectMap;
  console.log(detail);
  console.log(list);
  console.log(listMap);
  list.forEach(item => {
    if(item.id==detail.id){
      //点击复选框时切换选中
      item.checked=!item.checked;
      if(item.checked){
        //选中的放入已选列表，利用map避免重复
        listMap.set(item.id,item);
      }else{
        //未选中的从map中删除
        listMap.delete(item.id);
      }
    }
  });

  //列表是否全被选中了
  let flag=list.every(item=>{
    return item.checked;
  });

  //是否选中全选
  if(flag){
    this.setData({
      checkedAll: true
    })
  }else{
    this.setData({
      checkedAll: false
    })
  }

  console.log(listMap);

  this.setData({
    departList: list,
    listProjectMap: listMap
  })
},

 //隐藏部门
 onCloseDepart(){
  this.setData({
    projectShow: false,
  })
},

  //选择完项目确定事件
  onConfirmUser(){
    let listMap=this.data.listProjectMap;
    //map转成数组
    let arr=[...listMap.values()];

    //名字
    let names=[];
    let projectIds = [];
    arr.forEach(item => {
      names.push(item.name);
      projectIds.push(item.id);
		});

    let projectArr='editTaskObj.projectArr';
    let projectName='editInfo.projectName';
    let projectId='editTaskObj.projectIds';
    this.setData({
      [projectArr]: arr,
      [projectName]: names,
      [projectId]:projectIds
    })

    this.onCloseDepart();
  },

   //显示部门
   onShowDepart(){
     console.log();
     if (!this.data.isDisable){
      this.setData({
        projectShow: true
      })
      this.getDepartList();
     }
    
  },

  deleteTask(e){
      console.log(e);
      console.log("删除任务");
      Dialog.confirm({
        title: '确定删除这项任务吗',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(() => {
        console.log("aa");
        let detail = e.currentTarget.dataset.item;
        console.log(detail);
        const {editTaskObj} = this.data
        let paramObj = {
            className:'taskReocrd',
            data:{
              id: detail.id,
              validState:0,
            } 
        }
        console.log(paramObj);
        CommonService.goSave(paramObj).then(res=>{
          console.log(res);
          if (res.statusCode == 200 && res.data.success == true){
            if(parseInt(editTaskObj.taskType) === 2){
                this.deleteTaskList(paramObj.data);
            }
            Toast.success('成功');  
            this.setData({
              addTaskShow:false,
              isDisable:true,
            })
            setTimeout(() => {
              //返回列表页并刷新数据
              this.getList();
            }, 1000);
          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }else{
            console.log(res);
            Toast.fail('操作失败');
          }
        }).catch((error) => {
          console.log(error)
          Toast.fail('操作失败');
        })


    }).catch(() => {});
  },

  deleteTaskList(param){
    let data = param
    CommonService.deleteTaskSyncTaskPlan(data).then(res=>{

    })
  },

  onConfirmTask(e){
    console.log(e);
    const buttonFlg = e.detail.target.dataset.flg;
    this.setData({
      disabled:true
    })
    console.log(this.data);
    const {editTaskObj} = this.data
    editTaskObj.taskType = parseInt(editTaskObj.taskType)
    let data = {
      className:'taskReocrd',
      data:editTaskObj
    }
    console.log(data);
    CommonService.goSave(data).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        this.setData({
          disabled:false
        })
        //taskType:1 集体任务，集体任务更新后同步任务清单，把旧的任务做已取消处理，再生成新的任务
        if(data.data.taskType === 1){
            this.updateTaskList(data.data);
        }else{
            //taskType:2,巡检任务，巡检任务更新后，点击“确认并同步计划”按钮，执行同步巡检计划。等下一个生成周期
            //会自动生成任务清单
            if(buttonFlg === "saveAndSync"){
              this.syncTaskPlan(data.data);     
            }
        }
        Toast.success('成功');  
        this.setData({
          addTaskShow:false,
          isDisable:true,
        })
        setTimeout(() => {
          //返回列表页并刷新数据
          this.getList();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        console.log(res);
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      console.log(error)
      Toast.fail('操作失败');
    })
  },

  //同步巡检计划
  syncTaskPlan(param){
      let data = param
      CommonService.syncTaskPlan(data).then(res=>{

      })
  },

    //同步巡检计划
    deleteSyncTaskPlan(param){
      let data = param
      CommonService.syncTaskPlan(data).then(res=>{

      })
  },

  //更新任务清单数据
  updateTaskList(param){
      let data = {
        id:param.id,
        taskType:param.taskType
      }
      CommonService.updateCollectiveTaskToTaskList(data).then(res=>{})
  },

   //查询部门
   getDepartList(){
    console.log("111111111111");
    this.setData({
      departList: []
    })

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
				searchAll: true,
				isProject: true,
        selectFields: ['id','name','regionId','region','fid','fDepart','companyId','company','area','type']
      }
    }
    CommonService.goFindList(param).then(res=>{
      console.log(res);
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            name: item.name,
            id: item.id,
            obj: item
          });
        });
        let map=new Map();
        console.log();
        const {editTaskObj} = this.data
        editTaskObj.projectArr.forEach(item2 => {
          map.set(item2.id,item2);
        });
        let projectList=arr;
        projectList.forEach(item => {
          if(map.get(item.id)){
            console.log(item);
            item.checked=true;
          }
        });
        this.setData({
          listProjectMap: map,
          departList: arr
        })
      }
    }).catch((error) => {
    })
  },

   //关闭任务弹出层
   onCloseTaskPopup(){
    this.setData({
      addTaskShow:false,
    })
  },
   // 折叠项切换事件
   onCollapseChange(event) {
    console.log(event);
   this.setData({
     activeName: event.detail
   });
 },

 onTaskClick(event){
   console.log(event);
    // 获取传递的参数
    const taskObj = event.currentTarget.dataset.taskId;
    var nameArr = []
    if (taskObj.projectArr){
      taskObj.projectArr.forEach(item => {
        nameArr.push(item.name);
      });
    }
    var names = "editInfo.projectName"
    console.log('点击了任务:', taskObj);
    this.setData({
      addTaskShow:true,
      editTaskObj:taskObj,
      [names]:nameArr
    })
 }, 

 clearMessage(e) {
  console.log("0000000000000099999999999999999999999999");
  console.log(e);
  let field = e.target.dataset.message;
  let obj = {};
  obj[field] = "";
  obj['disabled'] = false; 
  this.setData(obj);
  const value = e.detail;
  let names = 'editTaskObj.taskObj.'+field
   // 更新 initTaskObj.name
   this.setData({
    [names]: value
  });
},


  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //显示项目
  onShowProject(){
    this.setData({
			showProjectSelect: true
    })
    this.getProjectList();
  },

  //查询项目
  getProjectList(){
    this.setData({
      projectList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        isProject:true,
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%' + this.data.valueSearchProject + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        arr.push({text:"全部",id:-1})
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });

        this.setData({
          projectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目
  onCloseProject(){
    this.setData({
      showProject: false,
      valueSearchProject:''
    })
  },

  onCloseProjectSelect(){
    this.setData({
      showProjectSelect: false,
      valueSearchProject:''
    })
  },

  //确认项目
  onConfirmProject(e){
    console.log(e);

    this.setData({
      projectId:e.detail.value.id,
      projectName:e.detail.value.text
    })
    this.onCloseProjectSelect();
    this.refreshListAndPage();
  },

  //搜索项目
  onChangeProjectVal(e){
    this.setData({
      valueSearchProject: e.detail
    })
    this.getProjectList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加/编辑
  goToAdd(e){
    console.log(e);
    let paramObj={};
    if(e.currentTarget.dataset.detail){
      let detail=e.currentTarget.dataset.detail;
      paramObj.id=detail.id;
    }
    wx.navigateTo({
      url: "/packageB/pages/onSitelnspectionAdd/onSitelnspectionAdd?paramObj="+JSON.stringify(paramObj)
    })
  },

  //显示删除确认框
  onDelete(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showDelete: true,
      deleteId:detail.id,
      deleteImei:detail.imei
		})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})
